﻿#region File and License Information
/*
<File>
	<License Type="BSD">
		Copyright © 2009 - 2012, Daniel Vaughan. All rights reserved.
	
		This file is part of Calcium (http://calciumsdk.net).

		Redistribution and use in source and binary forms, with or without
		modification, are permitted provided that the following conditions are met:
			* Redistributions of source code must retain the above copyright
			  notice, this list of conditions and the following disclaimer.
			* Redistributions in binary form must reproduce the above copyright
			  notice, this list of conditions and the following disclaimer in the
			  documentation and/or other materials provided with the distribution.
			* Neither the name of the <organization> nor the
			  names of its contributors may be used to endorse or promote products
			  derived from this software without specific prior written permission.

		THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
		ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
		WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
		DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY
		DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
		(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
		LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
		ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
		(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
		SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
	</License>
	<Owner Name="Daniel Vaughan" Email="danielvaughan@outcoder.com" />
	<CreationDate>2012-05-23 10:47:09Z</CreationDate>
</File>
*/
#endregion

using System;
using System.Linq;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;
using System.Windows.Media;

namespace DanielVaughan.Windows
{
	public class TextBoxBehaviors
	{
		#region Watermark Behavior

		static readonly DependencyProperty WatermarkBehaviorProperty = DependencyProperty.RegisterAttached(
			"WatermarkBehavior",
			typeof(WatermarkBehavior),
			typeof(TextBoxBehaviors),
			null);

		public static readonly DependencyProperty WatermarkProperty = DependencyProperty.RegisterAttached(
			"Watermark",
			typeof(string),
			typeof(TextBoxBehaviors),
			new PropertyMetadata(OnWatermarkChanged));

		public static string GetWatermark(DependencyObject dependencyObject)
		{
			return (string)dependencyObject.GetValue(WatermarkProperty);
		}

		public static void SetWatermark(DependencyObject dependencyObject, string value)
		{
			dependencyObject.SetValue(WatermarkProperty, value);
		}

		static void OnWatermarkChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
		{
			var textBox = d as TextBox;
			WatermarkBehavior behavior = GetOrCreateWatermarkBehavior(textBox);
			behavior.Value = e.NewValue.ToString();
		}

		static WatermarkBehavior GetOrCreateWatermarkBehavior(TextBox textBox)
		{
			var behavior = textBox.GetValue(WatermarkBehaviorProperty) as WatermarkBehavior;

			if (behavior == null)
			{
				behavior = new WatermarkBehavior(textBox);
				textBox.SetValue(WatermarkBehaviorProperty, behavior);
			}

			return behavior;
		}

		public class WatermarkBehavior
		{
			string watermarkText;

			public Control Target { get; set; }

			public string Value
			{
				get
				{
					return watermarkText;
				}
				set
				{
					if (watermarkText != value)
					{
						TextBox textBox = Target as TextBox;
						if (textBox != null && textBox.Text == watermarkText)
						{
							textBox.Text = value;
						}

						watermarkText = value;
					}
				}
			}

			public WatermarkBehavior(TextBox textBox)
			{
				Target = textBox;
				Target.GotFocus += HandleGotFocus;
				Target.LostFocus += HandleLostFocus;
				Target.Loaded += HandleLoaded;
			}

			void HandleLoaded(object sender, RoutedEventArgs e)
			{
				HandleLostFocus(sender, e);
			}

			void HandleGotFocus(object sender, RoutedEventArgs e)
			{
				TextBox textBox = sender as TextBox;
				if (textBox != null && textBox.Text == Value)
				{
					textBox.Text = String.Empty;
					textBox.Foreground = new SolidColorBrush(Colors.Black);
				}
			}

			void HandleLostFocus(object sender, RoutedEventArgs e)
			{
				TextBox textBox = sender as TextBox;
				if (textBox != null && (textBox.Text.Length == 0))
				{
					textBox.Text = Value;
					textBox.Foreground = new SolidColorBrush(Colors.Gray);
				}
			}
		}

		#endregion

		#region TextCleared

		static readonly DependencyProperty TextClearedProperty
			= DependencyProperty.RegisterAttached(
				"TextCleared",
				typeof(bool),
				typeof(TextBoxBehaviors),
				new PropertyMetadata(false));

		public static bool GetTextCleared(Control target)
		{
			return (bool)target.GetValue(TextClearedProperty);
		}

		public static void SetTextCleared(Control target, bool value)
		{
			target.SetValue(TextClearedProperty, value);
		}

		#endregion

		#region EnterKeyCommand

		static readonly DependencyProperty EnterKeyCommandBehaviorProperty
			= DependencyProperty.RegisterAttached(
				"EnterKeyCommandBehavior",
				typeof(EnterKeyCommandBehavior),
				typeof(TextBoxBehaviors),
				new PropertyMetadata(null));

		static readonly DependencyProperty EnterKeyCommandProperty 
			= DependencyProperty.RegisterAttached(
				"EnterKeyCommand",
				typeof(ICommand),
				typeof(TextBoxBehaviors),
				new PropertyMetadata(OnEnterKeyCommandChanged));


		public static ICommand GetEnterKeyCommand(TextBox target)
		{
			return (ICommand)target.GetValue(EnterKeyCommandProperty);
		}

		public static void SetEnterKeyCommand(TextBox target, ICommand value)
		{
			target.SetValue(EnterKeyCommandProperty, value);
		}

		static void OnEnterKeyCommandChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
		{
			TextBox textBox = d as TextBox;
			if (textBox == null)
			{
				throw new InvalidOperationException("EnterKeyCommandBehavior can only be used on a TextBox.");
			}

			EnterKeyCommandBehavior behavior = GetOrCreateEnterKeyCommandBehavior(textBox);

			if (e.NewValue != null)
			{
				behavior.Command = (ICommand)e.NewValue;
				textBox.SetValue(EnterKeyCommandBehaviorProperty, behavior);
				behavior.Attach();
			}
			else
			{
				textBox.SetValue(EnterKeyCommandBehaviorProperty, null);
				behavior.Detach();
			}
		}

		/// <summary>
		/// Retrieves the behavior if it has been previously associated, or creates a new behavior instance.
		/// </summary>
		static EnterKeyCommandBehavior GetOrCreateEnterKeyCommandBehavior(TextBox target)
		{
			var behavior = target.GetValue(EnterKeyCommandBehaviorProperty) as EnterKeyCommandBehavior;

			if (behavior == null)
			{
				behavior = new EnterKeyCommandBehavior {Target = target};
			}

			return behavior;
		}

		public class EnterKeyCommandBehavior
		{
			public TextBox Target { get; set; }
			public ICommand Command { get; set; }

			public void Attach()
			{
				Target.KeyDown += OnKeyDown;
			}

			public void Detach()
			{
				Target.KeyDown -= OnKeyDown;
			}

			void OnKeyDown(object sender, KeyEventArgs e)
			{
				if (e.Key == Key.Enter)
				{
					Page parent = Target.GetVisualAncestors<Page>().FirstOrDefault();
					if (parent != null)
					{
						parent.Focus();
					}

					Command.Execute(Target.Text);
					if ((bool)Target.GetValue(TextClearedProperty))
					{
						Target.Text = string.Empty;
					}
				}
			}
		}

		#endregion
	}
}
